/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fee.entity.Profit;
import com.jeeplus.modules.fee.entity.Receivable;
import com.jeeplus.modules.fee.entity.Receivables;
import com.jeeplus.modules.fee.service.ReceivableService;
import com.jeeplus.modules.infor.entity.LoadDetil;
import com.jeeplus.modules.infor.entity.ProfitAnalysis;
import com.jeeplus.modules.infor.entity.RentDetil;
import com.jeeplus.modules.infor.service.LoadDetilService;
import com.jeeplus.modules.infor.service.RentDetilService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.entity.ReDetil;
import com.jeeplus.modules.infor.service.ReDetilService;

/**
 * 应收开票总报表Controller
 * @author 李超辉
 * @version 2018-09-29
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/reDetil")
public class ReDetilController extends BaseController {

	@Autowired
	private ReDetilService reDetilService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private RentDetilService rentDetilService;
	@Autowired
	private LoadDetilService loadDetilService;
	@Autowired
	private ReceivableService receivableService;
	
	@ModelAttribute
	public ReDetil get(@RequestParam(required=false) String id) {
		ReDetil entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = reDetilService.get(id);
		}
		if (entity == null){
			entity = new ReDetil();
		}
		return entity;
	}
	/**
	 * 应收开票列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "cx")
	public String cx(Date min, Date max, String pro) {
		jdbc.execute("delete from infor_redetil");
		Calendar c = Calendar.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		Date i=min;
		Date mixx;
		Date maxx;
		if(min==null||max==null){
			return "false";
		}
		while (i.getTime()<max.getTime()) {
			mixx=i;
			ReDetil reDetil=new ReDetil();
			reDetil.setDate(i);
			c.setTime(i);
			c.add(Calendar.MONTH, 1);
			i=c.getTime();
			maxx=i;
			//仓租
			RentDetil rentDetil=new RentDetil();
			//装卸
			LoadDetil loadDetil=new LoadDetil();
			//运输
			Receivable receivable=new Receivable();
			if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
				rentDetil.setPro(pro);
				loadDetil.setPro(pro);
				receivable.setProject(pro);
			}else if(!UserUtils.getUseroffice().equals("总部")){
				rentDetil.setPro(UserUtils.getUseroffice());
				loadDetil.setPro(UserUtils.getUseroffice());
				receivable.setProject(pro);
			}
			//仓租
			rentDetil.setDate(mixx);
			rentDetil.setQr(1);
            List<RentDetil> rens=rentDetilService.findList(rentDetil);
            double czys=0.0;
            double czkp=0.0;
            double czwkp=0.0;
			for(RentDetil r:rens){
				czys+=Double.parseDouble(r.getSrhs());
				if(r.getStatus().equals("已开票")){
					czkp+=Double.parseDouble(r.getSrhs());
				}else{
					czwkp+=Double.parseDouble(r.getSrhs());
				}
			}
			reDetil.setCzkp(nf.format(czkp).replaceAll(",",""));
			reDetil.setCzwkp(nf.format(czwkp).replaceAll(",",""));
			reDetil.setCzys(nf.format(czys).replaceAll(",",""));

			//装卸
			loadDetil.setDate(mixx);
            loadDetil.setQr(1);
            List<LoadDetil> ls=loadDetilService.findList(loadDetil);
            double zxys=0.0;
            double zxkp=0.0;
            double zxwkp=0.0;
            for(LoadDetil l:ls){
				zxys+=Double.parseDouble(l.getSrhs());
				if(l.getStatus().equals("已开票")){
					zxkp+=Double.parseDouble(l.getSrhs());
				}else{
					zxwkp+=Double.parseDouble(l.getSrhs());
				}
			}
			reDetil.setZxkp(nf.format(zxkp).replaceAll(",",""));
			reDetil.setZxwkp(nf.format(zxwkp).replaceAll(",",""));
			reDetil.setZxys(nf.format(zxys).replaceAll(",",""));

			//运输
			receivable.setMin(format.format(mixx));
            receivable.setMax(format.format(maxx));
            receivable.setStatus("2");
            List<Receivable> res=receivableService.findList(receivable);
            double ysys=0.0;
            double yskp=0.0;
            double yswkp=0.0;
            for(Receivable r:res){
				ysys+=Double.parseDouble(r.getHs());
				if(r.getStatus().equals("已开票")){
					yskp+=Double.parseDouble(r.getHs());
				}else{
					yswkp+=Double.parseDouble(r.getHs());
				}
			}
			reDetil.setYskp(nf.format(yskp).replaceAll(",",""));
			reDetil.setYswkp(nf.format(yswkp).replaceAll(",",""));
			reDetil.setYsys(nf.format(ysys).replaceAll(",",""));
			double zys=ysys+czys+zxys;
			double zkp=yskp+czkp+zxkp;
			double zwkp=yswkp+czwkp+zxwkp;
			reDetil.setZys(nf.format(zys).replaceAll(",",""));
			reDetil.setZkp(nf.format(zkp).replaceAll(",",""));
			reDetil.setZwkp(nf.format(zwkp).replaceAll(",",""));
			reDetilService.save(reDetil);
		}
		return "success";
	}
	/**
	 * 应收开票总报表列表页面
	 */
	@RequiresPermissions("infor:reDetil:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/reDetilList";
	}
	
		/**
	 * 应收开票总报表列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:reDetil:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ReDetil reDetil, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ReDetil> page = reDetilService.findPage(new Page<ReDetil>(request, response), reDetil); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑应收开票总报表表单页面
	 */
	@RequiresPermissions(value={"infor:reDetil:view","infor:reDetil:add","infor:reDetil:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ReDetil reDetil, Model model) {
		model.addAttribute("reDetil", reDetil);
		return "modules/infor/reDetilForm";
	}

	/**
	 * 保存应收开票总报表
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:reDetil:add","infor:reDetil:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ReDetil reDetil, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, reDetil)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		reDetilService.save(reDetil);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存应收开票总报表成功");
		return j;
	}
	
	/**
	 * 删除应收开票总报表
	 */
	@ResponseBody
	@RequiresPermissions("infor:reDetil:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ReDetil reDetil, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		reDetilService.delete(reDetil);
		j.setMsg("删除应收开票总报表成功");
		return j;
	}
	
	/**
	 * 批量删除应收开票总报表
	 */
	@ResponseBody
	@RequiresPermissions("infor:reDetil:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			reDetilService.delete(reDetilService.get(id));
		}
		j.setMsg("删除应收开票总报表成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:reDetil:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(ReDetil reDetil, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "应收开票总报表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ReDetil> page = reDetilService.findPage(new Page<ReDetil>(request, response, -1), reDetil);
    		new ExportExcel("应收开票总报表", ReDetil.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出应收开票总报表记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:reDetil:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ReDetil> list = ei.getDataList(ReDetil.class);
			for (ReDetil reDetil : list){
				try{
					reDetilService.save(reDetil);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条应收开票总报表记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条应收开票总报表记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入应收开票总报表失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/reDetil/?repage";
    }
	
	/**
	 * 下载导入应收开票总报表数据模板
	 */
	@RequiresPermissions("infor:reDetil:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "应收开票总报表数据导入模板.xlsx";
    		List<ReDetil> list = Lists.newArrayList(); 
    		new ExportExcel("应收开票总报表数据", ReDetil.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/reDetil/?repage";
    }

}